//二次封装axios
import axios from 'axios'
import { Message } from 'element-ui'
import router from '@/router'

//引入环境地址
import envConfig from './qqdi'

//创建axios实例
const service = axios.create({
    baseURL: envConfig.prodEnv.baseURL,
    timeout: 5000
})

//设置请求拦截器
service.interceptors.request.use(config => {
    console.log('请求拦截')
    return config
}, error => {})


//请求响应拦截器
service.interceptors.response.use(res => {
    console.log('响应拦截器：', res)
    const { meta: { msg, status: code } } = res.data;
    //后台成功返回的状态码
    const successStatusArr = [200, 201, 204]
    if (successStatusArr.includes(code)) {
        const { data: result } = res.data;
        //如果是登录成功，则将后台返回的token保存到本地
        if (res.config.url === '/login') {
            sessionStorage.setItem('token', result.token)
            router.push('/home')
        }
        //成功的提示
        Message({
            message: msg,
            type: 'success'
        })



        //返回成功后的数据
        return {
            result
        }
    }

    //失败
    Message({
        message: msg,
        type: 'error'
    })
    return Promise.reject(msg)
}, error => {})

export default service;